package com.bawei.module_detail.ui

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.mvi.base.BaseMVIFragment
import com.bawei.module_detail.adapter.CommentAdapter
import com.bawei.module_detail.databinding.FragmentCommentBinding
import com.bawei.module_detail.intent.CommentIntent
import com.bawei.module_detail.model.entity.CommentEntity
import com.bawei.module_detail.model.entity.SendCommentParam
import com.bawei.module_detail.state.CommentState
import com.bawei.module_detail.viewmodel.CommentViewModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date


class CommentFragment(
    val pauseVideo: () -> Unit,
    playVideo: () -> Unit,
    val item_id: String,
) : BaseMVIFragment() {
    private lateinit var binding : FragmentCommentBinding
    private lateinit var viewModel : CommentViewModel
    private lateinit var adapter: CommentAdapter
    private lateinit var list : List<CommentEntity>
    override fun generateViewModel() {
        viewModel = ViewModelProvider(requireActivity()).get(CommentViewModel::class.java)
    }

    //就看啥抠脚大汉

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCommentBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun initView() {
        super.initView()
        adapter = CommentAdapter()
        binding.rv.layoutManager = LinearLayoutManager(requireContext())
        binding.rv.adapter = adapter

    }

    override fun initData() {
        super.initData()
        handleGetComment(0, item_id)
        binding.tvWriteComment.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (s?.endsWith("\n") == true) {  // 检测回车符
                    val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
                    val param = SendCommentParam(
                        content = s.toString(),
                        time,
                        item_id.toLong(),
                        "",
                        "https://ts3.tc.mm.bing.net/th/id/OIP-C.g5M-iZUiocFCi9YAzojtRAAAAA?r=0&rs=1&pid=ImgDetMain&o=7&rm=3"
                    )
                    lifecycleScope.launch {
                        repeatOnLifecycle(Lifecycle.State.STARTED){
                            viewModel.intents.send(CommentIntent.getSendComment(param))
                        }
                    }
                    binding.tvWriteComment.setText(null)
                }
            }
        })
        //点击分享
        binding.sendShare.setOnClickListener {
            getShare()
            pauseVideo()
        }

    }
    fun handleGetComment(page: Int, videoId: String) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.intents.send(CommentIntent.getComment(page, videoId))
            }
        }
    }

    override fun handleState() {
        // 处理状态
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                viewModel.commentStateFlow.collect{
                    when(it){
                        CommentState.Empty -> {}
                        CommentState.init -> {}
                        is CommentState.onFailed -> {
                            Log.e("sss-----", "handleState: ${it.msg}")
                        }
                        is CommentState.onSuccess -> {
                            if (it.type == "put"){
                                list = it.list as List<CommentEntity>
                                adapter.setList(list)
                                adapter.notifyDataSetChanged()
                            }
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                viewModel.sendCommentStateFlow.collect{
                    when(it){
                        CommentState.Empty -> {
                        }
                        CommentState.init -> {
                        }
                        is CommentState.onFailed -> {
                            Log.e("sss----",it.msg)
                        }
                        is CommentState.onSuccess -> {
                            if (it.type == "send"){
                                Toast.makeText(requireContext(),"评论成功",Toast.LENGTH_SHORT).show()
                                //发送评论请求
                                viewModel.intents.send(CommentIntent.getComment(0,item_id))
                            }
                        }
                    }
                }
            }
        }
    }
}